<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
<template>
  <div>
    <Card class="mb-10">
      <Row>
        <Col span="12">
          <h3>电脑管理</h3>
        </Col>
        <Col span="12" class="text-right">
          <component2 v-if="Super">
            <Button type="primary" @click="addItem" class="mr-10">新建</Button>
          </component2>
          <component2 v-if="Super">
            <Button type="error" @click="myDelete">删除</Button>
          </component2>
        </Col>
      </Row>
    </Card>
    <Card>
      <Row style="margin-bottom: 10px;">
        <span>日期范围：</span>
        <DatePicker
          style="width:160px"
          type="date"
          format="yyyy-MM-dd"
          :value="createTime"
          @on-change="myStartTime"
          placeholder="开始日期"
        ></DatePicker>
        <span>~</span>
        <DatePicker
          style="width:160px;margin-right:20px;"
          type="date"
          format="yyyy-MM-dd"
          :value="shellTime"
          @on-change="myEndTime"
          placeholder="结束日期"
        ></DatePicker>
        <span>关键字：</span>
        <Input
          placeholder="请输入电脑品牌"
          v-model.trim="searchText"
          style="width:200px;margin-right:20px;"
        ></Input>
        <Button type="primary" @click="search">搜索</Button>
      </Row>
      <Table
        size="large"
        @on-selection-change="selectOption"
        stripe
        ref="selection"
        :columns="tableCol"
        :data="tableData"
      ></Table>
      <Page
        class="mt-10 text-right"
        :total="total"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="changePage"
        @on-page-size-change="changeSize"
        show-sizer
        show-total
      />
    </Card>
    <Modal v-model="saveItem" :title="itemTitle" @on-cancel="closeSaveItem">
      <Form ref="formData" :model="formData" :label-width="80">
        <input type="hidden" name="id" v-model="formData.id" />
        <FormItem label="电脑品牌">
          <Input v-model="formData.dname" placeholder="请添加电脑品牌" :maxlength="10"></Input>
        </FormItem>
        <FormItem label="电脑类型">
          <Row>
            <Col span="12" style="padding-right:10px">
              <Select v-model="formData.pid" filterable>
                <Option v-for="item in computerList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="电脑颜色">
          <Input v-model="formData.color" placeholder="请填写颜色" :maxlength="11"></Input>
        </FormItem>
        <FormItem label="出厂时间">
          <DatePicker
            style="width:160px"
            type="date"
            format="yyyy-MM-dd"
            v-model="formData.createTime"
            placeholder="请填写出厂日期"
          ></DatePicker>
        </FormItem>
        <FormItem label="出售时间">
          <DatePicker
            style="width:160px"
            type="date"
            format="yyyy-MM-dd"
            v-model="formData.shellTime"
            placeholder="请填写出售日期"
          ></DatePicker>
        </FormItem>
        <FormItem label="图片">
          <div>
            <div>
              <img :src="imageSrc" style="width:200px;height:200px;" />
            </div>
            <Upload
              ref="upload"
              :show-upload-list="true"
              name="name"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :format="['jpg','jpeg','png']"
              type="drag"
              action="api/computer/uploadImg"
              style="display: inline-block;width:150px;"
            >
              <Button type="primary" style="width:150px;" >上传图片</Button>
            </Upload>
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="closeSaveItem">关闭</Button>
        <Button type="primary" :disabled="saveItemStatu" @click="saveItemOk">确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { hasOneOf } from "@/libs/tools";
import {
  computerTableData,
  updateComputer,
  commentDel1,
  addComputer,
  getAllComputerType
} from "@/api/data";
export default {
  data() {
    return {
      uploadList: [],
      takeImg: "",
      imageSrc: "",
      searchText: "", // 搜索内容初始化
      pageSize: 10,
      currentPage: 1,
      total: 1,
      startTime: "", // 日期初始化
      endTime: "", // 日期初始化

      formData: {}, //表单信息
      addUser: true, //是否为新增用户

      upLoadPic: false, // 照片上传模态框
      picture: [], //照片上传
      teacherId: 0, //照片上传参数

      saveItem: false, //保存操作框
      saveItemStatu: false, //保存点击状态
      itemTitle: "新建电脑", //保存操作框title

      selectItemArr: [], // 选中项目id
      tableCol: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "ID",
          key: "id"
        },
        {
          title: "类型",
          key: "computerType",
          render: (h, params) => {
            console.log("++++++" + JSON.stringify(params));
            var oName = params.row.computerType;
            return h("div", [h("span", {}, oName.name)]);
          }
        },
        {
          title: "品牌",
          key: "dname"
        },
        {
          title: "颜色",
          key: "color"
        },
        {
          title: "出厂时间",
          key: "createTime"
        },
        {
          title: "出售时间",
          key: "shellTime"
        },
        {
          title: "图片",
          key: "picture",
          render: (h, params) => {
            return h("img", {
              style: {
                width: "100px",
                height: "50px"
              },
              attrs: {
                src: "http://" + params.row.picture
              }
            });
          }
        },
        {
          width: 100,
          title: "操作",
          key: "examineStatus",
          checkAccess: ["superAdmin"],
          render: (h, params) => {
            console.log();
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "large",
                    disabled: this.viewAccessComputer
                  },
                  on: {
                    click: () => {
                      let getData = JSON.parse(
                        JSON.stringify(this.tableData[params.index])
                      );
                      this.formData = getData;
                      this.itemTitle = "编辑电脑信息";
                      this.imageSrc = "http://" + params.row.picture;
                      this.addUser = false;
                      this.saveItem = true;
                      if (this.computerList.length >= 1) {
                        return;
                      }
                      getAllComputerType().then(res => {
                        if (res.data.success) {
                          this.computerList = res.data.result.data;
                        } else if (res.data.errorMsg) {
                          this.$Message.warning({
                            content: res.data.errorMsg
                          });
                        }
                      });
                    }
                  }
                },
                "编辑"
              )
            ]);
          }
        }
      ],
      tableData: [],
      imgName: "",
      picShow: false,
      targetKeys: [],
      computerList: [],
      listStyle: {
        width: "150px",
        height: "200px"
      }
    };
  },
  methods: {
    async pageInit() {
      computerTableData(
        this.pageSize,
        this.currentPage,
        this.createTime,
        this.shellTime,
        this.searchText
      ).then(res => {
        if (res.data.success) {
          this.total = res.data.result.data.totalSize;
          this.tableData = res.data.result.data.pageList;
        } else if (res.data.errorMsg) {
          this.$Message.warning({
            content: res.data.errorMsg
          });
        }
      });
    },
    handleBeforeUpload(file) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        this.imageSrc = e.target.result;
      };
      return true;
    },
    handleSuccess(res, file) {
      this.takeImg = res.result.url;
      return takeimg;
    },
    handleError(error, file) {
      this.$Message.error("图片导入失败！");
    },

    changePage(page) {
      this.currentPage = page;
      this.pageInit();
    },
    changeSize(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.pageInit();
    },
    addItem() {
      this.$refs.upload.clearFiles();
      this.formData = {};
      this.itemTitle = "添加电脑";
      this.imageSrc = this.takeImg;
      this.addUser = true;
      this.saveItem = true;
      if (this.computerList.length >= 1) {
        return;
      }
      getAllComputerType().then(res => {
        if (res.data.success) {
          this.computerList = res.data.result.data;
        } else if (res.data.errorMsg) {
          this.$Message.warning({
            content: res.data.errorMsg
          });
        }
      });
    },

    closeUpload() {
      alert(1);
      this.upLoadPic = false;
      this.uploadList = [];
    },
    // 关闭保存项目模态框
    closeSaveItem() {
      this.formData = {};
      this.saveItem = false;
      this.targetKeys = [];
    },
    saveItemOk() {
      var that = this;
      var formData = this.formData;
      this.formData.picture=this.takeImg;
      //console.log(JSON.stringify(formData))
      if (!formData.dname) {
        this.$Message.warning({
          content: "请填写电脑品牌！"
        });
        return;
      } else if (!/[\u4e00-\u9fa5_a-zA-Z]+$/.test(formData.dname)) {
        this.$Message.warning({
          content: "请填写正确的电脑品牌"
        });
        return;
      }

      if (!formData.pid) {
        this.$Message.warning({
          content: "请填写电脑类型"
        });
        return;
      } else if (!/^[0-99]*$/.test(formData.pid)) {
        this.$Message.warning({
          content: "请填写正确的电脑类型"
        });
        return;
      }
      if (!formData.color) {
        this.$Message.warning({
          content: "请填写电脑颜色！"
        });
        return;
      } else if (!/[\u4e00-\u9fa5_a-zA-Z]+$/.test(formData.color)) {
        this.$Message.warning({
          content: "请填写正确的电脑颜色"
        });
        return;
      }
      if (!formData.shellTime) {
        this.$Message.warning({
          content: "请填写电脑出售时间！"
        });
        return;
      } else if (!/[\d{4}-\d{2}-\d{2}]*$/.test(formData.shellTime)) {
        this.$Message.warning({
          content: "请填写正确的出售时间"
        });
        return;
      }
       if (!formData.createTime) {
        this.$Message.warning({
          content: "请填写电脑出厂时间！"
        });
        return;
      } else if (!/[\d{4}-\d{2}-\d{2}]*$/.test(formData.createTime)) {
        this.$Message.warning({
          content: "请填写正确的出厂时间"
        });
        return;
      }
      if (formData.createTime > formData.shellTime) {
        this.$Message.warning({
          content: "出售时间怎么比出场时间还早"
        });
        return;
      }if (!formData.picture) {
        this.formData.picture="ptr36rer8.bkt.clouddn.com/d197639e-857d-4f48-acfd-4de284b39f3b";
        console.log("+++++++++++"+this.formData.picture);
      }
      if (this.addUser) {
        addComputer(this.formData, this.targetKeys).then(res => {
          // console.log(JSON.stringify(res))
          if (res.data.result && res.data.result.error) {
            this.$Message.warning({
              content: res.data.result.error
            });
            return;
          } else if (res.data.success) {
            this.$Message.success({
              content: "保存成功"
            });
            that.saveItem = false;
            that.pageInit();
          } else if (res.data.errorMsg) {
            this.$Message.warning({
              content: res.data.errorMsg
            });
          }
          that.saveItemStatu = false;
        });
      } else {
        this.saveItemStatu = true;
        updateComputer(this.formData, this.targetKeys).then(res => {
          // var that = this;
          that.saveItemStatu = false;
          if (res.data.success) {
            this.$Message.success({
              content: "修改成功"
            });
            that.saveItem = false;
            that.pageInit();
          } else if (res.data.errorMsg) {
            this.$Message.warning({
              content: res.data.errorMsg
            });
          }
        });
      }
    },
    // 选中项
    selectOption(selection, row) {
      this.selectItemArr = [];
      for (let item of selection) {
        this.selectItemArr.push(item.id);
      }
    },
    // 删除
    myDelete() {
      var selectItemArr = this.selectItemArr;
      if (selectItemArr.length < 1) {
        this.$Message.warning({
          content: "请选择项目！"
        });
        return;
      }
      commentDel1("/computer/deleteComputerByIds", selectItemArr).then(res => {
        console.log(JSON.stringify(res));
        if (res.data.success) {
          this.selectItemArr = [];
          this.pageInit();
          this.$Message.success({
            content: "删除成功！"
          });
        } else if (res.data.errorMsg) {
          this.$Message.warning({
            content: res.data.errorMsg
          });
        }

        // this.tableData = res.data.result.data.pageList;
      });
    },
    // 开始日期
    myStartTime(newTime) {
      this.createTime = newTime;
    },
    // 结束日期
    myEndTime(newTime) {
      this.shellTime = newTime;
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.pageInit();
    },
    handleChange(newTargetKeys) {
      this.targetKeys = newTargetKeys;
    },
    render(item) {
      return item.label;
    },
    reloadMockData() {
      this.transfer = this.getMockData();
      this.targetKeys = this.getTargetKeys();
    }
  },
  mounted() {
    // 初始化
    computerTableData(10, 1).then(res => {
      console.log("----" + JSON.stringify(res));
      if (res.data.success) {
        this.total = res.data.result.data.totalSize;
        this.tableData = res.data.result.data.pageList;
        var getalltime = [];
        for (var i = 0; i < this.tableData.length; i++) {
          getalltime.push(this.tableData[i].createTime);
        }
        console.log(getalltime);
      } else if (res.data.errorMsg) {
        this.$Message.warning({
          content: res.data.errorMsg
        });
      }
    });
    // 图片上传
    this.uploadList = this.$refs.upload.fileList;
  },

  computed: {
    access() {
      return this.$store.state.user.access;
    },
    //所有权限
    viewAccessAll() {
      return hasOneOf(["superAdmin", "computer", "student"], this.access);
    },
    //部分权限
    viewAccessComputer() {
      return hasOneOf(["computer", "student"], this.access);
    },
    Super() {
      return hasOneOf(["superAdmin"], this.access);
    }
  }
};
</script>
